package com.ruoyi.manage.service.impl;

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.manage.domain.DeviceSequence;
import com.ruoyi.manage.mapper.DeviceSequenceMapper;
import com.ruoyi.manage.service.IDeviceSequenceService;

/**
 * 设备顺序编码Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class DeviceSequenceServiceImpl implements IDeviceSequenceService
{
    @Autowired
    private DeviceSequenceMapper deviceSequenceMapper;

    /**
     * 获取并更新顺序编码
     * 
     * @return 五位顺序编码
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getAndUpdateSequence()
    {
        // 获取当前顺序编码
        DeviceSequence sequence = deviceSequenceMapper.selectCurrentSequence();
        String newCode;
        
        if (sequence == null) {
            // 如果编码不存在，初始化编码为00001
            newCode = "00001";
            sequence = new DeviceSequence();
            sequence.setCode(newCode);
            sequence.setUpdateTime(new Date());
            deviceSequenceMapper.initSequence(sequence);
        } else {
            // 如果编码存在，将其加1并格式化为5位
            try {
                int codeNum = Integer.parseInt(sequence.getCode());
                codeNum++;
                newCode = String.format("%05d", codeNum);
            } catch (NumberFormatException e) {
                // 如果解析失败，默认为00001
                newCode = "00001";
            }
            
            // 更新数据库中的编码
            sequence.setCode(newCode);
            sequence.setUpdateTime(new Date());
            deviceSequenceMapper.updateSequence(sequence);
        }
        
        return newCode;
    }
}